from PyQt5.Qt import *
from resource.login import Ui_Form

from API.APItool import APItool

class DownloadCaptchaThread(QThread):   # 多线程类
    get_captcha_signal=pyqtSignal(str)
    auto_DM_signal=pyqtSignal(str)
    def run(self):
        url = APItool.downloadCaptcha()

        print("下载验证码")
        self.get_captcha_signal.emit(url)

    def autoDM(self):
        # 连接自动打码平台
        result=""
        self.current_url
        self.auto_DM_signal.emit(result)

class LoginPanel(QWidget, Ui_Form):
    successLogin=pyqtSignal(str)
    def __init__(self, parent=None, *args, **kwargs):
        super().__init__(parent, *args, **kwargs)
        self.setupUi(self)
        self.refreshCaptcha()  # 初始化窗口时，刷新验证码

    def refreshCaptcha(self):
        print("刷新验证码")
        # 请求下载的验证码图片显示在label标签上
        thread=DownloadCaptchaThread(self)  # 开辟一个子线程
        def donwloadCaptcha(url):
            self.current_url = url
            pixmap = QPixmap(url)
            self.captcha_label.setPixmap(pixmap)
            self.captcha_label.clearPoint()  # 点击刷新按钮后清除验证码图片上的按钮红点
        thread.get_captcha_signal.connect(donwloadCaptcha)
        thread.start()

    def autoDM(self):
        print("自动打码")
        self.captcha_label.autoAddPoint([1, 2, 3, 4, 5, 6, 7, 8])

    def loginCheck(self):
        print("登录验证")
        self.captcha_label.clearPoint()  # 点击登录按钮后清除验证码图片上的按钮红点
        result = self.captcha_label.getResult()  # 接收点击过的坐标位置字符串
        if len(result)==0:
            QMessageBox.about(self,"提示","请填写验证码！")
            return None
        if APItool.checkCaptcha(result):  # 判断返回是否正确
            print("验证码正确")
            account = self.password_le.text()
            password = self.account_le.text()
            success=APItool.checkAccount(account,password)
            print(success,"传输成功")
            if success is None:
                QMessageBox.warning(self,"错误提示","账号或者密码错误！")
                return None
            self.sucessLogin.emit(success)

        else:
            # print("验证码错误")
            QMessageBox.warning(self, "提示", "验证码错误！")
            self.refreshCaptcha()  # 验证码错误时，自动刷新验证码

    def loginButtonEnabled(self):
        # 监听两个文本框是否有内容，控制登录按钮是否可用
        if len(self.password_le.text()) > 6 and len(self.account_le.text()) > 0:
            self.login_btn.setEnabled(True)
        else:
            self.login_btn.setEnabled(False)


if __name__ == '__main__':
    import sys

    app = QApplication(sys.argv)
    login_panel = LoginPanel()

    login_panel.show()

    sys.exit(app.exec_())
